package com.lawliet.example.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lawliet.example.config.ImportDataListener;
import com.lawliet.example.model.User;
import com.lawliet.example.model.vo.Result;
import com.lawliet.example.service.IUserService;
import com.lawliet.example.util.QueryHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RequestMapping("/user")
@RestController
@Tag(name = "用户管理")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;


    /**
     *
     * @param data 查询条件
     * @param pageNo 当前页
     * @param pageSize 没页显示条数
     * @param req
     * @return
     */
    @Operation(summary = "分页列表查询",description = "分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(@Parameter(description = "查询条件") User data,
                                   @Parameter(description = "当前页") @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @Parameter(description = "每页显示条数") @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                    HttpServletRequest req) {

        Page<User> page = new Page<>(pageNo, pageSize);
        IPage<User> pageList = userService.page(page, QueryHelper.buildQueryWrapper(data));

        return Result.OK(pageList);
    }

    @Operation(summary = "导出")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<User> dataList = userService.list();

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户数据")
                .doWrite(dataList);
    }

    @Operation(summary = "导入")
    @PostMapping("/importExcel")
    public Result<?> importExcel(@RequestParam(value = "file") MultipartFile file) throws IOException {

        EasyExcel.read(file.getInputStream(), User.class, new ImportDataListener<User>(userService)).sheet().doRead();

        return Result.OK("导入成功！！！");
    }


}
